#ifndef UNNORMALCLIENTSTATISTICDIALOG_H
#define UNNORMALCLIENTSTATISTICDIALOG_H

#include <QDialog>
#include <QTableWidget>
#include <vector>
#include <QHash>
#include <QSet>
#include <boost/shared_ptr.hpp>

#include "singleclient.h"
#include "clientgroup.h"
#include "tempunnormal.h"
#include "humiunnormal.h"
#include "glassbroken.h"
#include "doorbroken.h"
#include "powersupplylow.h"
#include "screenunnormal.h"
#include "childwindowbase.h"

namespace Ui {
    class UnnormalClientStatisticDialog;
}

class UnnormalClientStatisticDialog : public ChildWindowBase {
    Q_OBJECT
public:
	UnnormalClientStatisticDialog(ChildWindowBase *parent = 0);
    ~UnnormalClientStatisticDialog();
private slots:
	void onExportExcelButton();
protected:
    void changeEvent(QEvent *e);
private:
	template <class UnnormalStateType>
			void eachColumnCount(int column, const QHash<UnnormalStateType*,boost::shared_ptr<SingleClient> >&, const QHash<int,int>& groupIdToTableInde);
	void doStatistic();

private:
    Ui::UnnormalClientStatisticDialog *ui;
	QTableWidget* m_Table;
};

template <class UnnormalStateType>
		void UnnormalClientStatisticDialog::eachColumnCount(
				int column,
				const QHash<UnnormalStateType*,boost::shared_ptr<SingleClient> >& unnormalList,
				const QHash<int,int>& groupIdToTableIndex)
{
	int allCount = m_Table->rowCount()-1;

	std::vector<int> eachGroupCount;
	eachGroupCount.resize(allCount);
	for(size_t i = 0; i < eachGroupCount.size(); ++i)
		eachGroupCount[i] = 0;

	QSet<int> clientIsChecked;
	int unnormalCount = 0;

	for(typename QHash<UnnormalStateType*,boost::shared_ptr<SingleClient> >::const_iterator it = unnormalList.begin();
	it != unnormalList.end();
	++it)
	{
		if(it.key()->getHandled() == 0) //////////
		{
			UnnormalStateType* unnormalSate = it.key();
			boost::shared_ptr<SingleClient> client = unnormalSate->getClient();
			if(clientIsChecked.find(client->getId()) != clientIsChecked.end())
				continue;
			clientIsChecked.insert(client->getId());
			int index = groupIdToTableIndex[client->getBelongGroup()->getId()];
			++eachGroupCount[index];
			++unnormalCount;
		}
	}

	for(size_t i = 0; i < eachGroupCount.size(); ++i)
	{
		QTableWidgetItem *eachGroupCountItem = new QTableWidgetItem(QString::number(eachGroupCount[i]));
		if(eachGroupCount[i] != 0)
		{
			eachGroupCountItem->setTextColor(QColor("red"));
		}
		m_Table->setItem(i, column, eachGroupCountItem);
	}

	QTableWidgetItem *allCountItem = new QTableWidgetItem(QString::number(unnormalCount));
	if(unnormalCount != 0)
	{
		allCountItem->setTextColor(QColor("red"));
	}
	m_Table->setItem(allCount, column, allCountItem);
}

#endif // UNNORMALCLIENTSTATISTICDIALOG_H
